<template>
  <view class="container">
    <!-- 铅封基本信息区域 -->
    <view class="sealno-info-section">
      <view class="sealno-info-row">
        <text class="sealno-info-label">铅封编号</text>
        <text class="sealno-info-value">{{ sealInfo.snCode }}</text>
      </view>
      <view class="sealno-info-row">
        <view class="sealno-info-item">
          <text class="sealno-info-label">铅封种类</text>
          <text class="sealno-info-value">{{ sealInfo.snType }}</text>
        </view>
        <view class="sealno-info-item">
          <text class="sealno-info-label">当前状态</text>
          <text class="sealno-info-value" :style="sealnoStatusDict[sealInfo.snStatus]?.style || {}">
            {{ sealnoStatusDict[sealInfo.snStatus]?.text || sealInfo.snStatus }}
          </text>
        </view>
      </view>
      <view class="sealno-info-row">
        <view class="sealno-info-item">
          <text class="sealno-info-label">所属单位</text>
          <text class="sealno-info-value">{{ sealInfo.deptName }}</text>
        </view>
        <view class="sealno-info-item">
          <text class="sealno-info-label">车辆信息</text>
          <text class="sealno-info-value">{{ sealInfo.vehicleInfo || '暂无数据' }}</text>
        </view>
      </view>
      <view class="sealno-info-row">
        <view class="sealno-info-item">
          <text class="sealno-info-label">施打人</text>
          <text class="sealno-info-value">暂无数据</text>
        </view>
        <view class="sealno-info-item">
          <text class="sealno-info-label">施打对象</text>
          <button class="sealno-info-device-select-btn"
                  @click="openUnsealDeviceSelector"
                  :disabled="!!deviceId || isDeviceSelectDisabled"> <!-- 增加 isDeviceSelectDisabled 判断 -->
            {{ unsealDeviceInfo.name || '暂无数据' }}
          </button>
        </view>
      </view>
    </view>
    <!-- 边界线区域 -->
    <view class="divider">
      <view class="divider-line"></view>
      <text class="divider-text">溯源信息</text>
      <view class="divider-line"></view>
    </view>

    <!-- 溯源信息列表区域 -->
    <scroll-view class="operate-info-section" scroll-y>
      <view v-for="(item, index) in sealInfo.mobileSealnoOperateSubDTOList" :key="index" class="operate-info-item">
        <text class="operate-info-time">{{ item.time }}</text>
        <text class="operate-info-text">{{ item.content }}</text>
      </view>
    </scroll-view>
    <!-- 底部按钮区域 -->
    <view class="action-btn-section">
      <button class="action-btn-confirm" @click="handleConfirm">确认验收</button>
      <button class="action-btn-report" @click="handleReport">异常上报</button>
    </view>

    <!-- 拆封设备选择弹窗区域 -->
    <uni-popup ref="unsealDeviceSelector" type="center">
      <view class="unseal-device-selection-content">
        <view class="unseal-device-selection-header">
          <text class="unseal-device-selection-title">拆封设备选择</text>
          <uni-icons type="close" size="24" @click="closeUnsealDeviceSelector"/>
        </view>
        <view class="unseal-device-selection-body">
          <view class="unseal-device-selection-area">
            <input
                v-model="searchKeyword"
                placeholder="请选择配送计划"
                class="search-input"
            />
            <button class="search-btn" @click="searchPlanList">搜索</button>
          </view>
          <!-- 搜索结果列表 -->
          <view class="search-results" v-if="planList.length > 0 && showSearchResults">
            <view
                class="result-item"
                v-for="item in planList"
                :key="item.value"
                @click="handlePlanSelect(item.value, item.text)"
            >
              {{ item.text }}
            </view>
          </view>
          <!-- 设备选择区域 -->
          <view class="unseal-device-selection-area" v-if="selectedPlan">
            <view class="device-select-tip">
              请选择车牌号为【{{ selectedPlanPlateNo }}】车辆的设备
            </view>
            <uni-data-select
                v-model="selectedDevice"
                :localdata="deviceList"
                :placeholder="`请选择车牌号为【${selectedPlanPlateNo}】车辆的设备`"
            />
          </view>
          <view class="unseal-device-selection-info" v-if="selectedDevice">
            <text class="unseal-device-selection-label">绑定铅封编号</text>
            <text class="unseal-device-selection-value">{{ unsealDeviceInfo.sealNo || '暂无数据' }}</text>
          </view>
        </view>
        <view class="unseal-device-selection-footer">
          <button class="unseal-device-selection-cancel" @click="closeUnsealDeviceSelector">取消</button>
          <button class="unseal-device-selection-confirm" @click="confirmUnsealDevice">确认</button>
        </view>
      </view>
    </uni-popup>
    <!-- 异常设备选择弹窗区域 -->
    <uni-popup ref="errorDeviceSelector" type="center" :z-index="1001" class="error-device-selector-popup">
      <view class="error-device-selection-content">
        <view class="error-device-selection-header">
          <text class="error-device-selection-title">异常设备选择</text>
          <uni-icons type="close" size="24" @click="closeErrorDeviceSelector"/>
        </view>
        <view class="error-device-selection-body">
          <view class="error-device-selection-area">
            <input
                v-model="searchKeyword"
                placeholder="请选择配送计划"
                class="search-input"
            />
            <button class="search-btn" @click="searchPlanList">搜索</button>
          </view>
          <!-- 搜索结果列表 -->
          <view class="search-results" v-if="planList.length > 0 && showSearchResults">
            <view
                class="result-item"
                v-for="item in planList"
                :key="item.value"
                @click="handlePlanSelect(item.value, item.text)"
            >
              {{ item.text }}
            </view>
          </view>
          <!-- 设备选择区域 -->
          <view class="error-device-selection-area" v-if="selectedPlan">
            <view class="device-select-tip">
              请选择车牌号为【{{ selectedPlanPlateNo }}】车辆的设备
            </view>
            <uni-data-select
                v-model="selectedDevice"
                :localdata="deviceList"
                :placeholder="`请选择车牌号为【${selectedPlanPlateNo}】车辆的设备`"
            />
          </view>
          <view class="error设备选择信息" v-if="selectedDevice">
            <text class="error-device-selection-label">绑定铅封编号</text>
            <text class="error-device-selection-value">{{ errorDeviceInfo.sealNo || '暂无数据' }}</text>
          </view>
        </view>
        <view class="error-device-selection-footer">
          <button class="error-device-selection-cancel" @click="closeErrorDeviceSelector">取消</button>
          <button class="error-device-selection-confirm" @click="confirmErrorDevice">确认</button>
        </view>
      </view>
    </uni-popup>
    <!-- 异常警告弹窗区域 -->
    <uni-popup ref="alertWarningPopup" type="center">
      <view class="alert-warning-content">
        <view class="alert-warning-body">
          <uni-icons type="error" size="32" color="#ff0000"/>
          <text class="alert-warning-text">该设备存在异常情况，请确认是否继续？</text>
        </view>
        <view class="alert-warning-footer">
          <button class="alert-warning-reselect" @click="closeAlertWarningPopup">重新选择</button>
          <button class="alert-warning-report" @click="openReportPopup">异常上报</button>
        </view>
      </view>
    </uni-popup>
    <!-- 异常上报弹窗区域 -->
    <uni-popup ref="reportErrorPopup" type="center" :z-index="1000">
      <view class="report-error-content">
        <view class="report-error-header">
          <text class="report-error-title">异常上报</text>
          <uni-icons type="close" size="24" @click="closeReportErrorPopup"/>
        </view>
        <view class="report-error-body">
          <view class="report-error-upload">
            <text class="report-error-upload-label">铅封照片</text>
            <view class="report-error-upload-area">
              <!-- 图片预览区域 -->
              <view class="report-error-upload-preview" v-for="(img, index) in errorImages" :key="img.id">
                <image
                    :src="img.url"
                    mode="aspectFill"
                    @click="previewImage(img.url)"
                />
                <view class="report-error-preview-icon" @click.stop="previewImage(img.url)">
                  <uni-icons type="eye" size="20" color="#fff"></uni-icons>
                </view>
                <view class="report-error-delete-img" @click="deleteImage(index)">
                  <uni-icons type="close" size="20" color="#fff"></uni-icons>
                </view>
              </view>
              <!-- 上传按钮 -->
              <view class="report-error-upload-btn" @click="uploadImage" v-if="errorImages.length < 1">
                <uni-icons type="camera" size="32" color="#999"></uni-icons>
              </view>
            </view>
          </view>
          <view class="report-error-device">
            <text class="report-error-device-label">车辆设备</text>
            <button class="report-error-device-select-btn"
                    @click="openErrorDeviceSelector"
                    :disabled="isDeviceSelectDisabled">
              {{
                errorDeviceInfo.name || (reportDevice ? deviceList.find(item => item.value === reportDevice)?.text : '请选择车辆设备')
              }}
            </button>
          </view>
          <view class="report-error-description">
            <text class="report-error-description-label">异常描述</text>
            <textarea class="report-error-description-input" v-model="reportDescription" placeholder="请输入异常描述"/>
          </view>
        </view>
        <view class="report-error-footer">
          <button class="report-error-submit" @click="submitReport">提交</button>
        </view>
      </view>
    </uni-popup>
    <!-- 确认验收事件提示区域 -->
    <uni-popup ref="eventListPopup" type="center">
      <view class="event-list-content">
        <view class="event-list-header">
          <text class="event-list-title">铅封审批事件列表</text>
          <uni-icons type="close" size="24" @click="eventListPopup.close"/>
        </view>
        <view class="event-list-tip">
          <text>该铅封存在多个审批事件，请确认是否验收：</text>
        </view>
        <scroll-view class="event-list-body" scroll-y>
          <view v-for="(item, index) in eventList" :key="index" class="event-list-item">
            <text class="event-list-item-title">标题: {{ item.title }}</text>
            <text class="event-list-item-type">类型: {{ businessTypeDict[item.businessType] || item.businessType }}</text>
            <text class="event-list-item-status">状态: {{ flowStatusDict[item.status] || item.status }}</text>
          </view>
        </scroll-view>
        <view class="event-list-footer">
          <button class="event-list-cancel" @click="eventListPopup.close">取消</button>
          <button class="event-list-confirm" @click="confirmEventList">确认验收</button>
        </view>
      </view>
    </uni-popup>
    <view
        v-if="showCustomToast"
        class="custom-toast"
        :style="{ zIndex: 999999 }"
    >
      <text class="custom-toast-text">{{ toastMessage }}</text>
    </view>
  </view>
</template>
<script lang="ts" setup>
import {computed, getCurrentInstance, onMounted, ref, watch} from 'vue';
import {uploadFile} from "@/api/function/common/upload";
import {findSealnoOperateDetailBySnCode} from "@/api/function/sealnoOperate/sealnoOperate";
import {findAllDevice, findDeviceById, findSealNoByDeviceId} from "@/api/function/truck/truck";
import {findAllBillNo} from "@/api/function/truckBill/truckBill";
import {addSealnoFlow, findAllFlowBySnCode} from "@/api/function/sealnoFlow/sealnoFlow";
import {submitSealnoAcceptance} from "@/api/function/sealno/sealno";
import {findPlateNoByCustomSendBillNo} from "@/api/function/customSend/customSend";
import {sendTemplateCard} from "@/api/function/common/wechat";

const showCustomToast = ref(false);
const toastMessage = ref('');

const showToast = (message: string) => {
  toastMessage.value = message;
  showCustomToast.value = true;
  setTimeout(() => showCustomToast.value = false, 1500);
};

// 获取当前组件实例
const instance = getCurrentInstance();
const snCode = instance?.proxy?.$route.query.snCode as string;
const deviceId = instance?.proxy?.$route.query.deviceId as string;
const businessType = instance?.proxy?.$route.query.businessType as string;
const billNo = instance?.proxy?.$route.query.billNo as string;

const sealInfo = ref({
  snCode: '',
  snType: '',
  snStatus: '',
  deptName: '',
  vehicleInfo: ''
});

const sealnoStatusDict = {
  'ACTIVED': {text: '已入库', style: {color: '#52c41a'}},
  'LOCKED': {text: '锁定', style: {color: '#faad14'}},
  'USING': {text: '已使用', style: {color: '#1890ff'}},
  'UERSED': {text: '已作废', style: {color: '#bfbfbf'}},
  'DESTROYED': {text: '已销毁', style: {color: '#595959'}},
  'ERROR': {text: '异常', style: {color: '#ff4d4f'}}
};

const deviceNameDict = ref([
  { value: 'FUEL_TANK_METERING_PORT', text: '车罐计量口' },
  { value: 'FUEL_EXTERNAL_BREATHER_VALVE', text: '外置呼吸阀' },
  { value: 'FUEL_VAPOR_RECOVERY_VALVE', text: '油气回收阀' },
  { value: 'FUEL_MANHOLE_COVER', text: '入孔大盖' },
  { value: 'FUEL_FRONT_FILLING_VALVE', text: '前仓充装阀' },
  { value: 'FUEL_REAR_FILLING_VALVE', text: '后仓充装阀' }
]);

// 新增：事件类型字典
const businessTypeDict = {
  'BUY': '采购',
  'STORE': '入库',
  'TRANS': '调拨',
  'FIXED_WORK': '固封施打',
  'REPAIR': '车辆维修',
  'TRUCK_INIT': '新车施封',
  'CUSTOM_SEND': '小额配送',
  'SPECIAL': '异常施封'
};

// 新增：事件状态字典
const flowStatusDict = {
  'COMMIT': '已提交',
  'PASSED': '已通过',
  'RECECK': '二次审批',
  'REPASS': '二次审批通过',
  'FINISH': '已作业',
  'ERROR_FINISH': '异常结束'
};

// 定义两个容器
const unsealDeviceInfo = ref({ id: '', name: '', sealNo: '' }); // 拆封设备容器
const errorDeviceInfo = ref({ id: '', name: '', sealNo: '' }); // 异常设备容器

// 定义 selectedPlanPlateNo 容器
const selectedPlanPlateNo = computed(() => {
  const selected = planList.value.find(item => item.value === selectedPlan.value);
  const plateNo = selected?.plateNo || '';

  // 仅在 selectedPlan 有值时调用 findAllDevice
  if (selectedPlan.value && plateNo) {
    findAllDevice(plateNo).then(deviceResponse => {
      // 处理设备列表数据
      if (deviceResponse.code === 200 && deviceResponse.data) {
        deviceList.value = deviceResponse.data.map(item => ({
          value: item.id,
          text: deviceNameDict.value.find(dictItem => dictItem.value === item.name)?.text || item.name
        }));

        // 如果设备列表不为空，默认选中第一个设备
        if (deviceList.value.length > 0) {
          selectedDevice.value = deviceList.value[0].value;
        }
      } else {
        console.warn('未获取到设备列表数据');
        deviceList.value = [];
        selectedDevice.value = '';
      }
    }).catch(error => {
      console.error('调用 findAllDevice 失败：', error);
      deviceList.value = [];
      selectedDevice.value = '';
    });
  }

  return plateNo;
});

const isDeviceSelectDisabled = computed(() => {
  return ['REPAIR', 'TRUCK_INIT'].includes(businessType);
});

onMounted(async () => {
  console.log('接收到的参数：', {
    snCode,
    deviceId,
    businessType,
    billNo
  });

  try {
    const response = await findSealnoOperateDetailBySnCode(snCode);
    sealInfo.value = response.data;
  } catch (error) {
    console.error('调用 findSealnoOperateDetailBySnCode 失败：', error);
  }

  if (['REPAIR', 'TRUCK_INIT'].includes(businessType)) {
    try {
    const deviceResponse = await findDeviceById(deviceId);
      console.log('findDeviceById 返回数据:', deviceResponse); // 打印返回值
      // 从 deviceNameDict 中查找对应的 text
      const deviceName = deviceNameDict.value.find(item => item.value === deviceResponse.data.name)?.text || deviceResponse.data.name;
      // 更新 unsealDeviceInfo 和 errorDeviceInfo
      unsealDeviceInfo.value.name = deviceName;
      errorDeviceInfo.value.name = deviceName;
      selectedDevice.value = deviceId;
      console.log("selectedDevice",selectedDevice);
      reportDevice.value = deviceId;
      console.log("reportDevice",reportDevice);
    } catch (error) {
      console.error('调用 findDeviceById 失败：', error);
    }
  }

  fetchPlanList();
});

// 获取配送计划号数据
const fetchPlanList = async (keyword = '') => {
  try {
    let response;
    if (businessType === 'CUSTOM_SEND') {
      response = await findPlateNoByCustomSendBillNo(billNo);
      console.log("response", response);
      // 将返回的字符串封装成一个数组
      planList.value = [{
        value: billNo,
        text: billNo,
        plateNo: response.data
      }];
    } else {
      response = await findAllBillNo(keyword);
      // 将 planList 转换为普通数组
      planList.value = response.data.map(item => ({
        value: item.billNo,
        text: item.billNo,
        plateNo: item.plateNo
      }));
    }
  } catch (error) {
    console.error('调用接口失败：', error);
  }
};

const handlePlanSelect = async (value, text) => {
  selectedPlan.value = value;
  searchKeyword.value = text; // 更新输入框显示
  showSearchResults.value = false; // 隐藏搜索结果

  // 触发原有逻辑（加载设备列表）
  const selectedItem = planList.value.find(item => item.value === value);
  if (selectedItem) {
    await fetchAllDevice(selectedItem.plateNo);
  }
};

const fetchAllDevice = async (plateNo: string) => {
  try {
    const deviceResponse = await findAllDevice(plateNo); // 使用已导入的接口
    if (deviceResponse.code === 200 && deviceResponse.data) {
      // 转换设备列表格式（与现有逻辑一致）
      deviceList.value = deviceResponse.data.map(item => ({
        value: item.id,
        text: deviceNameDict.value.find(dictItem => dictItem.value === item.name)?.text || item.name
      }));

      // 自动选中第一个设备（如果存在）
      if (deviceList.value.length > 0 && !selectedDevice.value) {
        selectedDevice.value = deviceList.value[0].value;
      }
    } else {
      console.warn('未获取到设备列表数据');
      deviceList.value = [];
      selectedDevice.value = '';
    }
  } catch (error) {
    console.error('调用 findAllDevice 失败：', error);
    deviceList.value = [];
    selectedDevice.value = '';
  }
};

const searchKeyword = ref('');
const showSearchResults = ref(false);
// 修改 handlePlanSearch 方法
const handlePlanSearch = (value) => {
  searchKeyword.value = value;
};

// 搜索配送计划
const searchPlanList = async () => {
  try {
    showSearchResults.value = true; // 显示搜索结果
    let response;

    if (businessType === 'CUSTOM_SEND') {
      // 自定义发送业务类型，直接使用 billNo
      response = await findPlateNoByCustomSendBillNo(billNo);
      planList.value = [{
        value: billNo,
        text: billNo,
        plateNo: response.data
      }];
    } else {
      // 普通搜索
      response = await findAllBillNo(searchKeyword.value.trim());
      planList.value = response.data.map(item => ({
        value: item.billNo,
        text: item.billNo,
        plateNo: item.plateNo
      }));
    }

    if (planList.value.length === 0) {
      showToast('未找到匹配的配送计划');
    }
  } catch (error) {
    console.error('搜索失败:', error);
    showToast('搜索失败，请重试');
  }
};

const warningPopup = ref();
const reportErrorPopup = ref();
const selectedPlan = ref('');
const selectedDevice = ref('');
const reportDescription = ref('');
const reportDevice = ref('');
const planList = ref([]);
const deviceList = ref([]);
const openReportPopup = () => {
  warningPopup.value.close();
  reportErrorPopup.value.open();
};
// 新增：存储事件列表的响应式变量
const eventList = ref([]);
// 新增：事件列表弹窗的 ref
const eventListPopup = ref();
const confirmEventList = async () => {
  try {
    // 调用提交验收接口
    const acceptanceRes = await submitSealnoAcceptance(snCode, 'UERSED', selectedDevice.value);
    if (acceptanceRes.code === 200) {
      uni.showModal({
        title: '提示',
        content: '确认验收成功，即将返回首页',
        showCancel: false,
        success: () => {
          // 返回首页
          uni.switchTab({
            url: '/pages/index'
          });
        }
      });
    } else {
      showToast(`确认验收失败\n原因：${acceptanceRes.msg || '未知错误'}`);
    }
  } catch (error) {
    console.error('调用 submitSealnoAcceptance 失败:', error);
    showToast('确认验收失败，请重试');
  } finally {
    // 关闭弹窗
    eventListPopup.value.close();
  }
};
const handleConfirm = async () => {
  console.log("selectedDevice", selectedDevice.value);
  // 打印施打对象名称和设备 ID
  const selectedDeviceItem = deviceList.value.find(item => item.value === selectedDevice.value);
  if (selectedDeviceItem) {
    console.log('施打对象名称:', selectedDeviceItem.text);
    console.log('设备ID:', selectedDeviceItem.value);
  }
  const currentDeviceId = deviceId || selectedDevice.value;
  if (!currentDeviceId) {
    showToast('请先选择设备');
    return;
  } else {
    try {
      const deviceResponse = await findDeviceById(selectedDevice.value);
      console.log('findDeviceById 返回数据:', deviceResponse); // 打印设备信息
      // 取出 snId 并判断是否为空
      const snNo = deviceResponse.data?.snNo;

      if (!snNo) {
        uni.showModal({
          title: '提示',
          content: `您选择的设备还未施打铅封，不能执行拆封操作，请重新选择或异常上报！`,
          confirmText: '重新选择',
          cancelText: '异常上报',
          success: (res) => {
            if (res.confirm) {
              // 用户选择重新选择
              selectedDevice.value = '';
            } else if (res.cancel) {
              // 用户选择异常上报
              handleReport();
            }
          }
        });
        return; // 如果已绑定铅封，直接返回，不继续后续操作
      }
    } catch (error) {
      console.error('调用 findDeviceById 失败:', error);
      return;
    }
  }
  try {
    const res = await findAllFlowBySnCode(snCode);
    console.log('findAllFlowBySnCode 返回数据:', res);
    if (res.code === 200) {
      // 将事件列表存储到响应式变量中
      eventList.value = res.data;
      // 检查是否存在事件申请
      if (res.data && res.data.length > 0) {
        // 打开事件列表弹窗
        eventListPopup.value.open();
      } else {
        // 不存在事件申请，直接处理确认验收逻辑
        const acceptanceRes = await submitSealnoAcceptance(snCode, 'UERSED', selectedDevice.value);
        if (acceptanceRes.code === 200) {
          uni.showModal({
            title: '提示',
            content: '确认验收成功，即将返回首页',
            showCancel: false,
            success: () => {
              // 返回首页
              uni.switchTab({
                url: '/pages/index'
              });
            }
          });
        } else {
          showToast(`确认验收失败\n原因：${acceptanceRes.msg || '未知错误'}`);
        }
      }
    } else {
      showToast(`确认验收失败\n原因：${res.msg || '未知错误'}`);
    }
  } catch (error) {
    console.error('调用 findAllFlowBySnCode 失败:', error);
    showToast('确认验收失败，请重试');
  }
};
// 清空多个值的方法
const resetValues = () => {
  selectedPlan.value = ''; // 清空配送计划号
  reportDescription.value = ''; // 清空异常描述
  // 如果是 REPAIR 或 TRUCK_INIT，不清空设备相关数据
  if (!['REPAIR', 'TRUCK_INIT'].includes(businessType)) {
    selectedDevice.value = ''; // 清空设备选择
    reportDevice.value = ''; // 清空上报设备
  }
};
const handleReport = () => {
  resetValues(); // 调用清空方法
  reportErrorPopup.value.open();
};
// 定义 errorImages 容器，用于存储上传的图片信息
const errorImages = ref<Array<{ id: string; url: string; fileName: string }>>([]);
const uploadImage = () => {
  uni.chooseImage({
    count: 1, // 每次选择一张图片
    sizeType: ['compressed'], // 压缩图片
    sourceType: ['camera', 'album'], // 支持相机和相册
    success: async (res) => {
      try {
        const tempFilePath = res.tempFilePaths[0];
        uni.showLoading({
          title: '上传中...',
          mask: true
        });
        const uploadRes = await uploadFile({
          filePath: tempFilePath,
          formData: {}
        });
        if (uploadRes.code === 200) {
          // 将上传成功的图片信息添加到列表中
          errorImages.value.push({
            id: uploadRes.data.id,
            url: uploadRes.data.url,
            fileName: uploadRes.data.fileName
          });
        } else {
          showToast('上传失败');
        }
      } catch (error) {
        console.error('上传失败:', error);
        showToast('上传失败，请重试');
      } finally {
        uni.hideLoading();
      }
    }
  });
};

const previewImage = (url: string) => {
  uni.previewImage({
    current: url, // 当前预览的图片
    urls: errorImages.value.map(img => img.url), // 所有图片的URL
    zIndex: 999999 // 设置更高的层级
  });
};

const deleteImage = (index: number) => {
  errorImages.value.splice(index, 1); // 删除指定索引的图片
};
const submitReport = async () => {
  // 校验异常描述
  if (!reportDescription.value.trim()) {
    showToast('请填写异常描述');
    return;
  }
  console.log("reportDevice",reportDevice);
  // 校验车辆设备
  if (!reportDevice.value) {
    showToast('请选择车辆设备');
    return;
  }

  // 校验铅封照片
  if (errorImages.value.length === 0) {
    showToast('请上传铅封照片');
    return;
  }

  try {
    // 封装提交数据
    const submitData = {
      snCode: sealInfo.value.snCode,
      fileIds: errorImages.value.map(img => img.id).join(','),
      deviceId: selectedDevice.value,
      errorDescription: reportDescription.value,
      businessNo: selectedPlan.value
    };

    // 调用接口
    const res = await addSealnoFlow(submitData);
    console.log("异常事件新增返回：", res);
    if (res.code === 200) {
      const currentUrl = window.location.href; // 获取完整 URL
      const domainPart = currentUrl.split('/pages/function')[0]; // 分割出域名部分
      const targetPath = '/pages/function/myToDo/index'; // 固定目标路径
      const url = `${domainPart}${targetPath}`; // 拼接完整 URL
      console.log("url",url);
      // 获取事件ID
      const flowId = res.data;
      await sendTemplateCard(flowId, url);
      // 关闭弹窗
      reportErrorPopup.value.close();
      // 显示成功提示
      uni.showModal({
        title: '提示',
        content: '异常上报成功',
        showCancel: false,
        success: () => {
          // 返回首页
          uni.switchTab({
            url: '/pages/index'
          });
        }
      });
    } else {
      // 处理接口返回的错误
      showToast('提交失败');
    }
  } catch (error) {
    console.error('提交失败:', error);
    showToast('提交失败，请重试');
  }
};
const unsealDeviceSelector = ref(); // 添加拆封设备选择弹窗的ref

const openUnsealDeviceSelector = () => {
  resetValues(); // 调用清空方法
  currentPopupType.value = 'unseal'; // 新增：标记为拆封弹窗
  unsealDeviceSelector.value.open(); // 打开拆封设备选择弹窗
};

const closeUnsealDeviceSelector = () => {
  searchKeyword.value = '';
  showSearchResults.value = false;
  selectedPlan.value = '';
  unsealDeviceSelector.value.close();
};

const confirmUnsealDevice = async () => {
  if (!selectedDevice.value) {
    showToast('请选择车辆设备');
    return;
  }

  const selectedDeviceItem = deviceList.value.find(item => item.value === selectedDevice.value);
  if (selectedDeviceItem) {
    try {
      const res = await findSealNoByDeviceId(selectedDevice.value);
      if (res.code === 200 && res.data) {
        // 检查设备绑定的铅封编号是否与页面铅封编号一致
        if (res.data !== sealInfo.value.snCode) {
          uni.showModal({
            title: '提示',
            content: `该设备已施打铅封【${res.data}】，不能对【${sealInfo.value.snCode}】进行拆封操作！`,
            confirmText: '重新选择',
            cancelText: '异常上报',
            success: (res) => {
              if (res.confirm) {
                // 用户选择重新选择
                selectedDevice.value = '';
              } else if (res.cancel) {
                // 用户选择异常上报
                handleReport();
              }
            }
          });
          return;
        }
        // 更新 unsealDeviceInfo
        Object.assign(unsealDeviceInfo.value, {
          id: selectedDeviceItem.value,
          name: selectedDeviceItem.text,
          sealNo: res.data // 确保 res.data 是字符串
        });
      } else {
        console.warn('获取铅封编号失败:', res.msg);
        // 如果设备未绑定铅封，弹窗提示用户
        uni.showModal({
          title: '提示',
          content: '您选择的设备未绑定铅封，请重新选择或异常上报',
          confirmText: '重新选择',
          cancelText: '异常上报',
          success: (res) => {
            if (res.confirm) {
              // 用户选择重新选择
              selectedDevice.value = '';
            } else if (res.cancel) {
              // 用户选择异常上报
              handleReport();
            }
          }
        });
        return;
      }
    } catch (error) {
      console.error('调用 findSealNoByDeviceId 失败:', error);
      Object.assign(unsealDeviceInfo.value, { sealNo: '暂无数据' });
    }
  }

  unsealDeviceSelector.value.close();
};

const alertWarningPopup = ref(); // 更新异常警告弹窗的ref

const closeAlertWarningPopup = () => {
  alertWarningPopup.value.close(); // 关闭异常警告弹窗
};

const closeReportErrorPopup = () => {
  reportErrorPopup.value.close(); // 关闭异常上报弹窗
};

const confirmErrorDevice = async () => {
  if (!selectedDevice.value) {
    showToast('请选择车辆设备');
    return;
  }

  const selectedDeviceItem = deviceList.value.find(item => item.value === selectedDevice.value);
  if (selectedDeviceItem) {
    try {
      const res = await findSealNoByDeviceId(selectedDevice.value);
      if (res.code === 200 && res.data) {
        // 更新 errorDeviceInfo
        Object.assign(errorDeviceInfo.value, {
          id: selectedDeviceItem.value,
          name: selectedDeviceItem.text,
          sealNo: res.data // 确保 res.data 是字符串
        });
      } else {
        console.warn('获取铅封编号失败:', res.msg);
        Object.assign(errorDeviceInfo.value, { sealNo: '暂无数据' });
      }
    } catch (error) {
      console.error('调用 findSealNoByDeviceId 失败:', error);
      Object.assign(errorDeviceInfo.value, { sealNo: '暂无数据' });
    }
  }

  reportDevice.value = selectedDevice.value;
  errorDeviceSelector.value.close();
};
const currentPopupType = ref<'unseal' | 'error' | null>(null); // 新增
watch(selectedDevice, async (newValue) => {
  console.log('selectedDevice 发生变化，新值:', newValue); // 打印新值
  console.log('当前弹窗类型:', currentPopupType.value); // 打印当前弹窗类型

  if (newValue && currentPopupType.value) {
    console.log('开始查找设备信息...'); // 打印开始查找设备信息
    const selectedDeviceItem = deviceList.value.find(item => item.value === newValue);
    if (selectedDeviceItem) {
      console.log('找到设备信息:', selectedDeviceItem); // 打印找到的设备信息

      try {
        console.log('开始调用 findSealNoByDeviceId 接口...'); // 打印接口调用开始
        const res = await findSealNoByDeviceId(newValue);
        console.log('findSealNoByDeviceId 返回数据:', res); // 打印接口返回数据

        if (res.code === 200) {
          console.log('成功获取铅封编号:', res.data); // 打印获取的铅封编号
          // 仅在弹窗中显示铅封编号，不更新页面的施打对象
          if (currentPopupType.value === 'unseal') {
            console.log('更新弹窗中的铅封编号...'); // 打印更新弹窗中的铅封编号
            unsealDeviceInfo.value.sealNo = res.data || '暂无数据';
          } else if (currentPopupType.value === 'error') {
            console.log('更新弹窗中的铅封编号...'); // 打印更新弹窗中的铅封编号
            errorDeviceInfo.value.sealNo = res.data || '暂无数据';
          }
        } else {
          console.warn('获取铅封编号失败:', res.msg);
        }
      } catch (error) {
        console.error('调用 findSealNoByDeviceId 失败:', error);
      }
    } else {
      console.warn('未找到匹配的设备信息'); // 打印未找到设备信息的警告
    }
  } else {
    console.warn('newValue 或 currentPopupType 为空，跳过处理'); // 打印跳过处理的警告
  }
});

const errorDeviceSelector = ref(); // 添加异常设备选择弹窗的ref

const openErrorDeviceSelector = () => {
  resetValues();
  currentPopupType.value = 'error'; // 新增：标记为异常弹窗
  if (['REPAIR', 'TRUCK_INIT'].includes(businessType)) {
    errorDeviceInfo.value.name = unsealDeviceInfo.value.name;
    reportDevice.value = deviceId; // 直接设置 reportDevice 为 deviceId
  } else {
    // 其他情况正常处理
    errorDeviceInfo.value.name = '';
    reportDevice.value = '';
  }
  errorDeviceSelector.value.open(); // 打开异常设备选择弹窗
};
const closeErrorDeviceSelector = () => {
  searchKeyword.value = '';
  showSearchResults.value = false;
  selectedPlan.value = '';
  errorDeviceSelector.value.close();
};
</script>
<style>
/* 公共区域 */
page {
  height: 100%;
}

.container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #ffffff;
}

/* 铅封基本信息区域 */
.sealno-info-section {
  padding: 40rpx 60rpx;
  margin: 0 30rpx;
  background-color: transparent;
  flex-shrink: 0;
  border-radius: 0;
}

.sealno-info-row {
  margin-bottom: 30rpx;
  display: flex;
}

.sealno-info-row:first-child {
  display: flex;
  flex-direction: column;
}

.sealno-info-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.sealno-info-label {
  color: #666666;
  font-size: 14px;
  margin-bottom: 12rpx;
  width: 160rpx;
}

.sealno-info-value {
  color: #333333;
  font-size: 16px;
}

.sealno-info-device-select-btn {
  background-color: rgba(0, 122, 255, 0.1);
  padding: 12rpx 30rpx;
  border-radius: 8rpx;
  color: #007AFF;
  font-size: 16px;
  margin: 0;
  height: 70rpx;
  line-height: 70rpx;
  border: 1px solid rgba(0, 122, 255, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 120rpx;
  white-space: nowrap;
  width: auto;
}

/* 边界线区域 */
.divider {
  display: flex;
  align-items: center;
  margin: 10rpx 0;
}

.divider-line {
  flex: 1;
  height: 2rpx;
  background-color: #e5e7eb;
}

.divider-text {
  margin: 0 20rpx;
  color: #6b7280;
  font-size: 14px;
}

/* 溯源信息列表区域 */
.operate-info-section {
  flex: 1;
  overflow: auto;
  padding: 30rpx 60rpx;
  margin: 30rpx 30rpx 30rpx 30rpx;
  background-color: transparent;
  border-radius: 20rpx;
}

.operate-info-item {
  margin-bottom: 30rpx;
}

.operate-info-time {
  display: block;
  color: #999999;
  font-size: 12px;
  margin-bottom: 8rpx;
}

.operate-info-text {
  display: block;
  color: #333333;
  font-size: 14px;
}

/* 底部按钮区域 */
.action-btn-section {
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  background-color: transparent;
  flex-shrink: 0;
  gap: 20rpx; /* 添加按钮之间的间距 */
}

.action-btn-confirm {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  background-color: #ff9900;
  color: #ffffff;
  font-size: 32rpx;
  border-radius: 8rpx;
  border: none;
  margin: 0;
}

.action-btn-report {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  background-color: #8c8c8c;
  color: #ffffff;
  font-size: 16px;
  border-radius: 8rpx;
  border: none;
  margin: 0;
}

/* 拆封设备选择弹窗区域 */
.unseal-device-selection-content {
  width: 600rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
}

.unseal-device-selection-header {
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eeeeee;
}

.unseal-device-selection-title {
  font-size: 18px;
  font-weight: bold;
}

.unseal-device-selection-body {
  padding: 30rpx;
}

.unseal-device-selection-area {
  margin-bottom: 30rpx;
}

.unseal-device-selection-info {
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
}

.unseal-device-selection-label {
  color: #666666;
  font-size: 14px;
  margin-bottom: 10rpx;
}

.unseal-device-selection-value {
  color: #333333;
  font-size: 16px;
}

.unseal-device-selection-footer {
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #eeeeee;
}

.unseal-device-selection-cancel {
  width: 240rpx;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  border-radius: 12rpx; /* 调整为方形圆角 */
  font-size: 16px;
  background-color: #f5f5f5; /* 浅灰色背景 */
  color: #666666; /* 深灰色文字 */
  border: 1px solid #e5e7eb; /* 浅灰色边框 */
  transition: all 0.3s ease; /* 添加过渡效果 */
}

.unseal-device-selection-cancel:active {
  background-color: #e5e7eb; /* 点击时加深背景色 */
}

.unseal-device-selection-confirm {
  width: 240rpx;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  border-radius: 12rpx; /* 调整为方形圆角 */
  font-size: 16px;
  background-color: #007AFF; /* 蓝色背景 */
  color: #ffffff; /* 白色文字 */
  border: 1px solid #007AFF; /* 蓝色边框 */
  transition: all 0.3s ease; /* 添加过渡效果 */
}

/* 异常设备选择弹窗区域 */
.error-device-selection-content {
  width: 600rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
}

.error-device-selector-popup {
  z-index: 1001 !important; /* 强制设置更高的层级 */
}

.error-device-selection-header {
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eeeeee;
}

.error-device-selection-title {
  font-size: 18px;
  font-weight: bold;
}

.error-device-selection-body {
  padding: 30rpx;
}

.error-device-selection-area {
  margin-bottom: 30rpx;
}

.error-device-selection-label {
  color: #666666;
  font-size: 14px;
  margin-bottom: 10rpx;
}

.error-device-selection-value {
  color: #333333;
  font-size: 16px;
}

.error-device-selection-footer {
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #eeeeee;
}

.error-device-selection-cancel {
  width: 240rpx;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  border-radius: 12rpx; /* 调整为方形圆角 */
  font-size: 16px;
  background-color: #f5f5f5; /* 浅灰色背景 */
  color: #666666; /* 深灰色文字 */
  border: 1px solid #e5e7eb; /* 浅灰色边框 */
  transition: all 0.3s ease; /* 添加过渡效果 */
}

.error-device-selection-cancel:active {
  background-color: #e5e7eb; /* 点击时加深背景色 */
}

.error-device-selection-confirm {
  width: 240rpx;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  border-radius: 12rpx; /* 调整为方形圆角 */
  font-size: 16px;
  background-color: #007AFF; /* 蓝色背景 */
  color: #ffffff; /* 白色文字 */
  border: 1px solid #007AFF; /* 蓝色边框 */
  transition: all 0.3s ease; /* 添加过渡效果 */
}

/* 异常警告弹窗区域 */
.alert-warning-content {
  width: 600rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
  padding: 40rpx;
}

.alert-warning-body {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 40rpx;
}

.alert-warning-text {
  margin-top: 20rpx;
  font: 16px;
  color: #333333;
  text-align: center;
}

.alert-warning-footer {
  display: flex;
  justify-content: space-between;
}

.alert-warning-reselect, .alert-warning-report {
  width: 240rpx;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  border-radius: 44rpx;
  font-size: 16px;
}

/* 异常上报弹窗区域 */
.report-error-content {
  width: 600rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
}

.report-error-header {
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eeeeee;
}

.report-error-title {
  font-size: 18px;
  font-weight: bold;
}

.report-error-body {
  padding: 30rpx;
}

.report-error-upload, .report-error-description, .report-error-device {
  margin-bottom: 30rpx;
}

.report-error-upload-label, .report-error-description-label, .report-error-device-label {
  display: block;
  color: #666666;
  font-size: 14px;
  margin-bottom: 10rpx;
}

.report-error-upload-area {
  display: flex;
  gap: 20rpx;
}

.report-error-description-input {
  width: 100%;
  height: 200rpx;
  padding: 20rpx;
  background-color: #f5f5f5;
  border-radius: 10rpx;
  font-size: 14px;
}

.report-error-footer {
  padding: 30rpx;
  border-top: 1px solid #eeeeee;
}

.report-error-submit {
  width: 100%;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  background-color: #007AFF;
  color: #ffffff;
  border-radius: 44rpx;
  font-size: 16px;
}

.report-error-device-select-btn {
  background-color: #ffffff; /* 白色背景 */
  padding: 12rpx 30rpx;
  border-radius: 8rpx;
  color: #333333; /* 深灰色文字 */
  font-size: 16px;
  margin: 0;
  height: 70rpx;
  line-height: 70rpx;
  border: 1px solid #e5e7eb; /* 浅灰色边框 */
  display: flex;
  align-items: center;
  justify-content: center;
  min-width: 120rpx;
  white-space: nowrap;
  width: auto;
}

.report-error-upload {
  margin-bottom: 30rpx;
}

.report-error-upload-label {
  display: block;
  color: #666666;
  font-size: 14px;
  margin-bottom: 10rpx;
}

.report-error-upload-preview {
  position: relative;
  width: 100px;
  height: 100px;
  border-radius: 8rpx;
  overflow: hidden;
}

.report-error-upload-preview image {
  width: 100%;
  height: 100%;
}

.report-error-preview-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  padding: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1;
}

.report-error-delete-img {
  position: absolute;
  top: 10rpx;
  right: 10rpx;
  width: 24rpx;
  height: 24rpx;
  line-height: 24rpx;
  text-align: center;
  background-color: rgba(255, 0, 0, 0.8);
  color: #fff;
  border-radius: 50%;
  font-size: 20rpx;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1; /* 确保删除图标在图片上方 */
}

.report-error-upload-btn {
  width: 100px;
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f5f5;
  border-radius: 8rpx;
  border: 1px dashed #d9d9d9;
}

/* 确认验收事件提示区域 */
.event-list-content {
  width: 600rpx;
  background-color: #ffffff;
  border-radius: 20rpx;
}

.event-list-header {
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #eeeeee;
}

.event-list-title {
  font-size: 18px;
  font-weight: bold;
}

.event-list-body {
  max-height: 400rpx;
  padding: 30rpx;
}

.event-list-item {
  margin-bottom: 20rpx;
}

.event-list-item-title {
  display: block;
  font-size: 16px;
  color: #333333;
}

.event-list-item-type, .event-list-item-status {
  display: block;
  font-size: 14px;
  color: #666666;
}

.event-list-footer {
  padding: 30rpx;
  display: flex;
  justify-content: space-between;
  border-top: 1px solid #eeeeee;
}

.event-list-cancel, .event-list-confirm {
  width: 240rpx;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  border-radius: 12rpx;
  font-size: 16px;
}

.event-list-cancel {
  background-color: #f5f5f5;
  color: #666666;
}

.event-list-confirm {
  background-color: #007AFF;
  color: #ffffff;
}

.event-list-tip {
  padding: 20rpx 30rpx;
  background-color: #f5f5f5;
  color: #666666;
  font-size: 14px;
}
/* 提示弹窗区域 */
.custom-toast {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  padding: 16rpx 32rpx;
  background-color: rgba(0, 0, 0, 0.8);
  color: #ffffff;
  border-radius: 8rpx;
  font-size: 14px;
  min-width: 150rpx;
  text-align: center;
  z-index: 999999;
}

/* 搜索区域样式 */
.flex-row {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.search-input {
  flex: 1;
  height: 70rpx;
  padding: 0 20rpx;
  border: 1px solid #e5e7eb;
  border-radius: 8rpx;
  font-size: 16px;
  color: #333;
}

.search-btn {
  background-color: #007AFF;
  color: #fff;
  padding: 0 24rpx;
  border-radius: 8rpx;
  white-space: nowrap;
  font-size: 16px;
  height: 70rpx;
  line-height: 70rpx;
  text-align: center;
  border: none;
}

.search-btn:active {
  background-color: #005eb3;
}

/* 搜索结果列表样式 */
.search-results {
  margin-top: 10rpx;
  max-height: 300rpx;
  overflow-y: auto;
  border: 1px solid #e5e7eb;
  border-radius: 8rpx;
  background-color: #fff;
  position: relative;
  z-index: 10;
}

.result-item {
  padding: 16rpx 20rpx;
  font-size: 16px;
  color: #333;
  border-bottom: 1px solid #e5e7eb;
}

.result-item:last-child {
  border-bottom: none;
}

.result-item:active {
  background-color: #f5f5f5;
}

.device-select-tip {
  color: #666666; /* 灰色文本 */
  font-size: 14px; /* 字体大小 */
  margin-bottom: 12rpx; /* 与下拉组件的间距 */
}
</style>
